//切换条件维度事件
$("#customCode").bind("change", function(){
    $("#customValue option").remove();
    $("#s2id_customValue span:first").html("请选择"+$("#s2id_customCode span:first").html());
    var custom = $("#customCode").val();
    if(custom==''){
        $("#s2id_customValue span:first").html("");
        return
    }
    $("#customValue").append("<option value='' >"+$("#s2id_customCode span:first").html()+"</option>");
    $.ajax({
        url: "/map/customList",
        type: "POST",
        data: {'custom': custom} ,
        success: function(result){
            for(var i=0; i < result.customList.length; i++){
                var values =  result.customList[i].label;
                var define =  result.customList[i].define;
                var obj = document.createElement("option");
                obj.value = values;
                obj.innerHTML=values+" "+define;
                $("#customValue").append(obj);
            }
        }
    });
});
$("#customCode").change();
//切换城市行政区事件
$("#city").bind("change", function(){
    $("#district option").remove();
    $("#s2id_district span:first").html("行政区");
    var city = $("#city").val()
    $("#district").append("<option value='-1' >行政区</option>")
    if(city=='-1'){
        return
    }
    $.ajax({
        url: "/estate/districtList",
        type: "POST",
        data: {'city': city} ,
        success: function(result){
            for(var i=0; i < result.districtList.length; i++){
                $("#district").append("<option value=" + result.districtList[i].zoneNumber + ">" + result.districtList[i].name + "</option>")
            }
        }
    });
});
// $("#city").change();
//切换城市地图事件
function search(){
    //清空搜索
    $('#word2').hide();
    $("#search").val("");
    $('#searchCommunity').html("");
    $('#searchCommunity').css('display','none');
    $('#district').val("");
    $("#s2id_district span:first").html("行政区");
    $('#risk').val("");
    $("#s2id_risk span:first").html("押品风险");
    $('#startDateStart').val("");
    $('#startDateEnd').val("");
    $('#buildArea').val("");
    $("#s2id_buildArea span:first").html("面积区段");
    $('#loansDuration').val("");
    $("#s2id_loansDuration span:first").html("抵押年限");
    $('#customCode').val("");
    $("#s2id_customCode span:first").html("已抵押数量");
    $("#customValue option").remove();
    $("#s2id_customValue span:first").html("");
    var zoneNumber = $("#city").val();
    var cityName = $("#city").find("option:selected").text();
    if((!zoneNumber || zoneNumber=="-1") && (!cityName || cityName=="请选择城市")){
        return;
    }
    map.centerAndZoom(cityName,13);
    map.enableScrollWheelZoom();
    scrollFlag = false;
    initMap(initMapUrl,{currentMap:currentMap,city:zoneNumber});
}
//参数改变事件
function searchData(map){//搜索条件改变事件
    var cluster = false;
    if(window.location.href.indexOf('cluster') != -1){
        cluster = true;
    }
    $('#word2').hide();
    //$('#searchCommunity').css('max-height','340px');
    $('#searchCommunity').css('display','block');
    $('#page').show();
    var inputData = getInputData();
    map.clearOverlays();
    if(currentMap=="pointMap"){
        pointOverlays.clearMarkers();
    }
    RequestData(communityUrl,inputData);
    if(allMapData.length==0 || mapDataStatus==false){
        $('#searchCommunity').css('display','none');
        $('#page').hide();
        return
    }
    searchFlag=true;
    scrollFlag=false;
    map.centerAndZoom(new BMap.Point(allMapData[0].lng, allMapData[0].lat),16);
    searchCommunityResult("searchCommunity",allMapData,cluster);
    createCommunity(allMapData);
}
//小区搜索结果HTML
function searchCommunityResult(id,paramsData,flag){
    $('#'+id+'').css('display','block');
    var html='';
    var Count = paramsData.length;//记录条数
    var PageSize=5;//设置每页示数目
    var PageCount=Math.ceil(Count/PageSize);//计算总页数
    var currentPage =1;//当前页，默认为1。
    var price;
    if(Count < 5){
        PageSize=Count;//设置每页示数目
        PageCount=1;//计算总页数
    }
    // 分页
    $('#page').pagination({
        currentPage: 1,
        totalPage: PageCount,
        isShow: false,
       // count: 5,
        prevPageText: "< 上一页",
        nextPageText: "下一页 >",
        callback: function (current) {
            //显示选择页的内容
                var selectPage=current;
                $('#searchCommunity li').remove();
                html = '';
                function size () {
                    if(Count-(selectPage-1)*PageSize < 6){
                        return Count;
                    }else{
                        return PageSize*selectPage;
                    }
                }
                for(i=(selectPage-1)*PageSize;i<size();i++){
                    price = paramsData[i].price/10000 + '万';
                    html+=
                        "<li><h5>"+(i+1)+"</h5><div><a style='display: block;font-size: 14px;' href = 'javascript:centerCommunity("+JSON.stringify(paramsData[i])+","+flag+")'>"+paramsData[i].communityName+"</a><p class='pull-right' style='color: #666; font-size: 12px;'>金额 <span style='color:#FF0000'>"+price+"</span></p><p style='color: #666;font-size: 12px;'>数量 <span style='color:#FF0000'>"+paramsData[i].count+"</span></p></div></li>";
                }
                $('#'+id+'').html(html);
                $('#'+id+' li').addClass('list-group-item media social-profile clearfix p-b-n');
                $('#'+id+' li h5').addClass('pull-left text-center p-n m-n');
                $('#'+id+' li div').addClass('media-body ');
        }
    });
    //显示默认页（第一页）
    for(var i=(currentPage-1)*PageSize;i<PageSize*currentPage;i++){
        //$('#table').append(paramsData[i]);
        price = paramsData[i].price/10000 + '万';
        html+=
            "<li><h5>"+(i+1)+"</h5><div><a style='display: block;font-size: 14px;' href = 'javascript:centerCommunity("+JSON.stringify(paramsData[i])+","+flag+")'>"+paramsData[i].communityName+"</a><p class='pull-right' style='color: #666; font-size: 12px;'>金额 <span style='color:#FF0000'>"+price+"</span></p><p style='color: #666;font-size: 12px;'>数量 <span style='color:#FF0000'>"+paramsData[i].count+"</span></p></div></li>";
    }
    $('#'+id+'').html(html);
    $('#'+id+' li').addClass('list-group-item media social-profile clearfix p-b-n');
    $('#'+id+' li h5').addClass('pull-left text-center p-n m-n');
    $('#'+id+' li div').addClass('media-body ');
    $('#searchCommunity li div p:first').css('float ','right');

    /*$.each(paramsData,function(i,obj){
        console.log(obj)
        var communityName = obj.communityName;
        var count = obj.count;
        html+=
            "<li><h5>"+(i+1)+"</h5><div><a href = 'javascript:centerCommunity("+JSON.stringify(obj)+")'>"+communityName+"</a><p>数量"+count+"</p></div></li>";
    });
    $('#'+id+'').html(html);
    $('#'+id+' li').addClass('list-group-item media social-profile clearfix p-b-n');
    $('#'+id+' li h5').addClass('pull-left text-center p-n m-n');
    $('#'+id+' li div').addClass('media-body ');*/
    // 点击小区进入楼栋
    // $('#'+id+' a').click(function(event){
    //     event.preventDefault();
    //     var inputData = getInputData();
    //     inputData.communityId=$(this).attr("href");
    //     map.clearOverlays();
    //     scrollFlag=false;
    //     if(currentMap=="clusterMap"){
    //         RequestData("/map/mapBuildingBankData",inputData);
    //     }else{
    //         RequestData(buildingUrl,inputData);
    //     }
    //     map.centerAndZoom(new BMap.Point(Community.lng, Community.lat),19);
    //     if(currentMap=="clusterMap"){
    //         createBuilding_bank(allMapData,boundaryData,pt,"abc.png",Community.communityName,Community.communityId);
    //     }else{
    //         searchBuildingResult(id,allMapData);
    //         createBuilding(allMapData);
    //     }
    //
    // })
}
//楼栋搜索结果HTML
function searchBuildingResult(id,paramsData){
    $('#'+id+'').css('display','block');
    var html='';
    var i = 1;
    paramsData.forEach(function(data){
        data.forEach(function(data){
            var estateList = data.estateList;
            estateList.forEach(function(data){
                html+=     "<li><h5>"+(i++)+"</h5><div><a class='linkMap' id='"+data.id+"'>"+data.sourceaddress+"</a><p>贷款金额："+data.loansamount+"元</p><p>放款日期："+data.startdate
                    +" | 贷款期数："+data.loansduration+"期</p><p>当前评估价："+data.loansevaluatetotalprice+"元 | 动态抵押率："+data.cltv+"%</p></div></li>"
            })
        })
    });
    $('#'+id+'').html(html);
    $('#'+id+' li').addClass('list-group-item media social-profile clearfix p-b-n');
    $('#'+id+' li h5').addClass('pull-left text-center p-n m-n');
    $('#'+id+' li div').addClass('media-body ');
    $('#'+id+' li p').addClass('m-n');
    $(".linkMap").click(function(){
        var href = window.location.origin + "/estate/mapShow/" + this.id;
        window.open(href);
    })
}
function centerCommunity(Community,flag){
    if(!flag)$('#page').hide();
    $('#word2').hide();
    $('#searchCommunity').show();
    var inputData = getInputData();
    inputData.communityId=Community.communityId;
    map.clearOverlays();
    scrollFlag=false;
    if(currentMap=="clusterMap"){
        RequestData("/map/mapBuildingBankData",inputData);
    }else{
        RequestData(buildingUrl,inputData);
    }
    var pt = new BMap.Point(Community.lng, Community.lat);
    map.centerAndZoom(pt,19);
    if(currentMap=="clusterMap"){
        createBuilding_bank(allMapData,boundaryData,pt,"abc.png",Community.communityName,Community.communityId);
    }else{
        searchBuildingResult("searchCommunity",allMapData);
        createBuilding(allMapData);
    }
}
function searchPicture(communityId){

    var purl="";
    var city = $("#city").val();
    $.ajax({
        type: "post",
        async: false,
        url: "/map/searchPicture",
        data: {
            communityId: communityId,
            city: city
        },
        success: function (data) {
            var pictureList=data.result.pictureList;
            var mapDataStatus = data.result.mapDataStatus;
            var length=pictureList.length;
            if(length==0 || mapDataStatus=='false'){
                purl="/assets/january.jpg"
            }else{
                purl=pictureList
            }
        }
    });
    return purl;
}
//页面参数
//小区联想搜索
//当键盘键被松开时发送Ajax获取数据
$('#search').keyup(function () {
    var paramsData = getInputData();
    var keywords = $(this).val();
    if (keywords == '') {
        $('#word2').hide();
        return
    };
    $.ajax({
        url: communityUrl,
        data:paramsData,
        dataType: 'json',
        type:"post",
        //jsonp: 'cb', //回调函数的参数名(键值)key
        // jsonpCallback: 'fun', //回调函数名(值) value
        beforeSend: function () {
            // $('#word').append('<div class="form-control">正在加载。。。</div>');
        },
        success: function (data) {
            $('#word2').empty().show();
            if (data.result.mapDataList.length==0 || data.result.mapDataList.mapDataStatus=="false") {
                $('#word2').append('<div class="error form-control">暂无相关数据</div>');
            }
            if(data.result.mapDataList.length<5){
                $.each(data.result.mapDataList, function (index,data) {
                    $('#word2').append("<a href = 'javascript:centerCommunity("+JSON.stringify(data)+")' class='click_work form-control nptText' >"+data.communityName+"</a>");
                });
            }else{
                for(var i=0;i<5;i++){
                    $('#word2').append("<a href = 'javascript:centerCommunity("+JSON.stringify(data.result.mapDataList[i])+")' class='click_work form-control nptText' >"+data.result.mapDataList[i].communityName+"</a>");
                }
            }
            $('.nptText').click(function () {
                $('#search').val($(this).html());
            })
        },
        error: function () {
            $('#word2').empty().show();
            $('#word2').append('<div class="click_work form-control">Fail "' + keywords + '"</div>');
        }
    })
});
function getInputData(){
    var communityName=$("#search").val(),
        city=$('#city').val(),
        district=$('#district').val(),
        risk=$('#risk').val(),
        startDateStart = $('#startDateStart').val(),
        startDateEnd = $('#startDateEnd').val(),
        buildArea=$('#buildArea').val(),
        customCode=$('#customCode').val(),
        customValue=$('#customValue').val(),
        loansDuration=$('#loansDuration').val(),
        inputData={
            communityName:communityName,
            city:city,
            district:district,
            risk:risk,
            startDateStart:startDateStart,
            startDateEnd:startDateEnd,
            buildArea:buildArea,
            loansDuration:loansDuration,
            currentMap:currentMap,
            customCode:customCode,
            customValue:customValue
        };
    return inputData;
}
function getDistrict(){
    $("#district option").remove();
    $("#s2id_district span:first").html("行政区");
    var city = $("#city").val()
    $("#district").append("<option value='-1' >行政区</option>")
    if(city=='-1'){
        return
    }
    $.ajax({
        url: "/estate/districtList",
        type: "POST",
        data: {'city': city} ,
        success: function(result){
            for(var i=0; i < result.districtList.length; i++){
                $("#district").append("<option value=" + result.districtList[i].zoneNumber + ">" + result.districtList[i].name + "</option>")
            }
        }
    });
}